package com.tangguangdi.shield.server.swagger;

import com.tangguangdi.base.common.entity.register.AppDefinition;
import com.tangguangdi.shield.server.permission.PermissionCache;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {

    public static final String API_URI = "/v2/api-docs";
    private final PermissionCache cache;


    @Override
    public List<SwaggerResource> get() {
        return getSwaggerResources();
    }

    private List<SwaggerResource> getSwaggerResources() {
        List<SwaggerResource> resources = new ArrayList<>();
        for (String key : cache.getApps().asMap().keySet()) {
            AppDefinition app = cache.getApps().asMap().get(key);
            SwaggerResource resource = swaggerResource(app);
            if (resource != null) {
                resources.add(resource);
            }
        }
        return resources;
    }


    private SwaggerResource swaggerResource(AppDefinition app) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(app.getName());
        swaggerResource.setLocation(app.getSwaggerPath()
                .concat(API_URI)
                .replaceAll("//", "/"));
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }

}
